package com.rocket.activity;

import java.util.ArrayList;
import java.util.Date;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.rocket.R;
import com.rocket.database.Missile83Sql;
import com.rocket.database.MissileJD89Sql;
import com.rocket.database.RocketBL1Sql;
import com.rocket.database.RocketHJD82Sql;
import com.rocket.database.RocketRYI6300Sql;
import com.rocket.database.RocketWR98Sql;
import com.rocket.database.WorkSql;
import com.rocket.database.WorkStationSql;
import com.rocket.entity.FirearmType;
import com.rocket.entity.Missile83;
import com.rocket.entity.MissileJD89;
import com.rocket.entity.Position;
import com.rocket.entity.RocketBL1;
import com.rocket.entity.RocketHJD82;
import com.rocket.entity.RocketRYI6300;
import com.rocket.entity.RocketWR98;
import com.rocket.entity.Work;
import com.rocket.entity.WorkStation;
import com.rocket.util.DialogUtil;
import com.rocket.util.MenuUtil;
import com.rocket.util.MyTextWatcher;

public class WorkAddActivity extends MenuActivity {

	private int				mFirearmType	= 0;

	Button					buttonBack;
	Button					buttonSave;
	TextView				tvFirearmType;
	EditText				etName;
	Button					btnName;
	EditText				etNumber;
	EditText				etFixedLon;
	EditText				etFixedLat;
	Button					btnFixedPosition;
	//	EditText				etMoveLon;
	//	EditText				etMoveLat;
	EditText				etHaiba;
	EditText				etCloudType;
	EditText				etCloudTop;
	EditText				etCloudBottom;
	EditText				etCenterHeight;
	EditText				etCloud6Height;
	LinearLayout			layoutRocket;
	TextView				tvRocketAngle;
	TextView				tvRocketHeight;
	TextView				tvRocketLength;
	Button					btnRocketQuery;
	LinearLayout			layoutMissile;
	TextView				tvMissileAngle;
	TextView				tvMissileTime;
	Button					btnMissileTime;
	TextView				tvMissileHeight;
	TextView				tvMissileLength;
	Button					btnMissileQuery;

	Button					btnFixedOrMove;

	ArrayList<WorkStation>	mStations;
	WorkStation				mStation;

	AlertDialog				dialog;

	boolean					isFixed			= true;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.workadd);

		mFirearmType = getIntent().getIntExtra("firearmtype", 0);

		buttonBack = (Button) findViewById(R.id.buttonback);
		buttonBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});

		buttonSave = (Button) findViewById(R.id.buttonsave);
		buttonSave.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (etName.getText().toString().trim().equals("")) {
					showToast("请输入作业点名");
					etName.requestFocus();
					return;
				}
				if (etNumber.getText().toString().trim().equals("")) {
					showToast("请输入作业点编号");
					etNumber.requestFocus();
					return;
				}
				if (etFixedLat.getText().toString().trim().equals("")) {
					showToast("请输入作业点纬度");
					etFixedLat.requestFocus();
					return;
				}
				if (etFixedLon.getText().toString().trim().equals("")) {
					showToast("请输入作业点经度");
					etFixedLon.requestFocus();
					return;
				}
				if (etHaiba.getText().toString().trim().equals("")) {
					showToast("请输入作业站点海拔高度");
					etHaiba.requestFocus();
					return;
				}
				if (etCloudTop.getText().toString().trim().equals("")) {
					showToast("请输入作业云顶高度");
					etCloudTop.requestFocus();
					return;
				}
				if (etCloudBottom.getText().toString().trim().equals("")) {
					showToast("请输入作业云底高度");
					etCloudBottom.requestFocus();
					return;
				}
				if (etCenterHeight.getText().toString().trim().equals("")) {
					showToast("作业云系强度中心高度");
					etCenterHeight.requestFocus();
					return;
				}
				if (etCloud6Height.getText().toString().trim().equals("")) {
					showToast("请输入作业云层-6°C高度");
					etCloud6Height.requestFocus();
					return;
				}
				if (mFirearmType < 10) {
					if (tvRocketAngle.getText().toString().trim().equals("")) {
						showToast("请查询火箭作业仰角");
						return;
					}
				} else if (mFirearmType > 10) {
					if (tvMissileAngle.getText().toString().trim().equals("")) {
						showToast("请查询高炮作业仰角");
						return;
					}
				}

				Work work = new Work();
				work.name = etName.getText().toString().trim();
				work.number = etNumber.getText().toString().trim();
				if (isFixed) {
					work.fixedLongitude = etFixedLon.getText().toString().trim();
					work.fixedLatitude = etFixedLat.getText().toString().trim();
				} else {
					work.moveLongitude = etFixedLon.getText().toString().trim();
					work.moveLatitude = etFixedLat.getText().toString().trim();
				}
				work.haiba = Integer.parseInt(etHaiba.getText().toString().trim());
				work.firearmType = mFirearmType;
				work.cloudType = etCloudType.getText().toString().trim();
				work.cloudTopHeight = Integer.parseInt(etCloudTop.getText().toString().trim());
				work.cloudBottomHeight = Integer.parseInt(etCloudBottom.getText().toString().trim());
				work.cloudCenterHeight = Integer.parseInt(etCenterHeight.getText().toString().trim());
				work.cloud6Height = Integer.parseInt(etCloud6Height.getText().toString().trim());
				if (mFirearmType < 10) {
					work.rocketAngle = Integer.parseInt(tvRocketAngle.getText().toString().trim());
					work.rocketMaxHeight = Integer.parseInt(tvRocketHeight.getText().toString().trim());
					work.rocketMaxLength = Integer.parseInt(tvRocketLength.getText().toString().trim());
				} else {
					work.missileAngle = Integer.parseInt(tvMissileAngle.getText().toString().trim());
					work.misseleTime = Integer.parseInt(tvMissileTime.getText().toString().trim());
					work.missileMaxHeight = Integer.parseInt(tvMissileHeight.getText().toString().trim());
					work.missileMaxLength = Integer.parseInt(tvMissileLength.getText().toString().trim());
				}
				Date date = new Date();
				date.setHours(0);
				date.setMinutes(0);
				date.setSeconds(0);
				work.createTime = date.getTime() / 100000 * 100000;
				WorkSql.getInstance().insert(work);

				if (mStation == null) {
					Position p = new Position(work.fixedLongitude, work.fixedLatitude);
					mStation = new WorkStation();
					mStation.positions.add(p);
					mStation.name = work.name;
					mStation.number = work.number;
					mStation.haiba = work.haiba;
					WorkStationSql.getInstance().insert(mStation);
				} else {
					Position p = new Position(work.fixedLongitude, work.fixedLatitude);
					if (!mStation.positions.contains(p)) {
						mStation.positions.add(p);
					}
					mStation.name = work.name;
					mStation.number = work.number;
					mStation.haiba = work.haiba;
					WorkStationSql.getInstance().update(mStation);
				}

				Intent intent = new Intent(WorkAddActivity.this, WorkInfoActivity.class);
				intent.putExtra("work", work);
				startActivity(intent);
				finish();
			}
		});

		tvFirearmType = (TextView) findViewById(R.id.tvtype);
		etName = (EditText) findViewById(R.id.etname);
		btnName = (Button) findViewById(R.id.btnname);
		btnName.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				//				ArrayAdapter<String> nameAdapter = new ArrayAdapter<String>(
				//						WorkAddActivity.this,
				//						android.R.layout.simple_list_item_single_choice);
				mStations = WorkStationSql.getInstance().query();
				//				for (WorkStation station : mStations) {
				//					nameAdapter.add(station.name);
				//				}
				ListView listview = new ListView(WorkAddActivity.this);
				listview.setAdapter(new BaseAdapter() {

					@Override
					public View getView(int position, View convertView, ViewGroup parent) {
						final WorkStation station = mStations.get(position);
						LinearLayout item;
						if (convertView == null) {
							item = (LinearLayout) getLayoutInflater().inflate(R.layout.workstation_item, null);
						} else {
							item = (LinearLayout) convertView;
						}
						item.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
						TextView text = (TextView) item.findViewById(R.id.text);
						text.setText(station.name);

						Button button = (Button) item.findViewById(R.id.button);
						button.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								WorkStationSql.getInstance().delete(station);
								mStations.remove(station);
								notifyDataSetChanged();
							}
						});

						return item;
					}

					@Override
					public long getItemId(int position) {
						return position;
					}

					@Override
					public Object getItem(int position) {
						return mStations.get(position).name;
					}

					@Override
					public int getCount() {
						return mStations.size();
					}
				});
				listview.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
						if (dialog != null) {
							dialog.dismiss();
						}
						mStation = mStations.get(arg2);
						etName.setText(mStation.name);
						etNumber.setText(mStation.number);
						etHaiba.setText(String.valueOf(mStation.haiba));
						etFixedLon.setText("");
						etFixedLat.setText("");
					}
				});
				dialog = new AlertDialog.Builder(WorkAddActivity.this).setTitle("选择站点").setView(listview).show();

			}
		});
		etNumber = (EditText) findViewById(R.id.etnumber);
		etFixedLon = (EditText) findViewById(R.id.etlon);
		etFixedLat = (EditText) findViewById(R.id.etlat);
		btnFixedPosition = (Button) findViewById(R.id.btnfixed);
		btnFixedPosition.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				ArrayAdapter<String> nameAdapter = new ArrayAdapter<String>(WorkAddActivity.this, android.R.layout.simple_list_item_single_choice);
				if (mStation != null && mStation.positions != null) {
					for (Position position : mStation.positions) {
						nameAdapter.add("经度：" + position.lon + "  纬度：" + position.lat);
					}
					ListView listview = new ListView(WorkAddActivity.this);
					listview.setAdapter(nameAdapter);
					listview.setOnItemClickListener(new OnItemClickListener() {

						@Override
						public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
							if (dialog != null) {
								dialog.dismiss();
							}
							Position p = mStation.positions.get(arg2);
							etFixedLon.setText(String.valueOf(p.lon));
							etFixedLat.setText(String.valueOf(p.lat));
						}
					});
					dialog = new AlertDialog.Builder(WorkAddActivity.this).setTitle("选择固定作业点").setView(listview).show();
				}
			}
		});
		//		etMoveLon = (EditText) findViewById(R.id.etmovelon);
		//		etMoveLat = (EditText) findViewById(R.id.etmovelat);
		etHaiba = (EditText) findViewById(R.id.ethaiba);
		etHaiba.addTextChangedListener(new MyTextWatcher(etHaiba));
		etCloudType = (EditText) findViewById(R.id.etcloudtype);
		etCloudTop = (EditText) findViewById(R.id.etcouldtop);
		etCloudTop.addTextChangedListener(new MyTextWatcher(etCloudTop));
		etCloudBottom = (EditText) findViewById(R.id.etcloudbottom);
		etCloudBottom.addTextChangedListener(new MyTextWatcher(etCloudBottom));
		etCenterHeight = (EditText) findViewById(R.id.etcloudcenter);
		etCenterHeight.addTextChangedListener(new MyTextWatcher(etCenterHeight));
		etCloud6Height = (EditText) findViewById(R.id.etcloud6height);
		etCloud6Height.addTextChangedListener(new MyTextWatcher(etCloud6Height));
		layoutRocket = (LinearLayout) findViewById(R.id.layoutrocket);
		tvRocketAngle = (TextView) findViewById(R.id.tvrocketangle);
		tvRocketHeight = (TextView) findViewById(R.id.tvrocketheight);
		tvRocketLength = (TextView) findViewById(R.id.tvrocketlength);
		btnRocketQuery = (Button) findViewById(R.id.btnrocketquery);
		btnRocketQuery.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (etHaiba.getText().toString().trim().equals("")) {
					showToast("请输入作业站点海拔高度");
					etHaiba.requestFocus();
					return;
				}
				if (etCenterHeight.getText().toString().trim().equals("")) {
					showToast("作业云系强度中心高度");
					etCenterHeight.requestFocus();
					return;
				}
				int centerHeight = Integer.parseInt(etCenterHeight.getText().toString().trim());
				int haiba = Integer.parseInt(etHaiba.getText().toString().trim());

				int height = centerHeight + haiba;

				switch (mFirearmType) {
				case FirearmType.ROCKET_WR98: {
					ArrayList<RocketWR98> rockets = RocketWR98Sql.getInstance().query();
					int i = 0;
					for (i = 0; i < rockets.size(); i++) {
						if (rockets.get(i).topHeight >= height) {
							break;
						}
					}
					if (i == rockets.size()) {
						i--;
					}
					RocketWR98 r = rockets.get(i);
					tvRocketAngle.setText(String.valueOf(r.angle));
					tvRocketHeight.setText(String.valueOf(r.topHeight));
					tvRocketLength.setText(String.valueOf(r.topLength));
					break;
				}
				case FirearmType.ROCKET_BL1: {
					ArrayList<RocketBL1> rockets = RocketBL1Sql.getInstance().query();
					int i = 0;
					for (i = 0; i < rockets.size(); i++) {
						if (rockets.get(i).topHeight >= height) {
							break;
						}
					}
					if (i == rockets.size()) {
						i--;
					}
					RocketBL1 r = rockets.get(i);
					tvRocketAngle.setText(String.valueOf(r.angle));
					tvRocketHeight.setText(String.valueOf(r.topHeight));
					tvRocketLength.setText(String.valueOf(r.topLength));
					break;
				}
				case FirearmType.ROCKET_HJD82: {
					ArrayList<RocketHJD82> rockets = RocketHJD82Sql.getInstance().query();
					int i = 0;
					for (i = 0; i < rockets.size(); i++) {
						if (rockets.get(i).topHeight >= height) {
							break;
						}
					}
					if (i == rockets.size()) {
						i--;
					}
					RocketHJD82 r = rockets.get(i);
					tvRocketAngle.setText(String.valueOf(r.angle));
					tvRocketHeight.setText(String.valueOf(r.topHeight));
					tvRocketLength.setText(String.valueOf(r.topLength));
					break;
				}
				case FirearmType.ROCKET_RY6300: {
					ArrayList<RocketRYI6300> rockets = RocketRYI6300Sql.getInstance().query();
					int i = 0;
					for (i = 0; i < rockets.size(); i++) {
						if (rockets.get(i).topHeight >= height) {
							break;
						}
					}
					if (i == rockets.size()) {
						i--;
					}
					RocketRYI6300 r = rockets.get(i);
					tvRocketAngle.setText(String.valueOf(r.angle));
					tvRocketHeight.setText(String.valueOf(r.topHeight));
					tvRocketLength.setText(String.valueOf(r.topLength));
					break;
				}
				default:
					break;
				}
			}
		});
		layoutMissile = (LinearLayout) findViewById(R.id.layoutmissile);
		tvMissileAngle = (TextView) findViewById(R.id.tvmissileangle);
		tvMissileTime = (TextView) findViewById(R.id.tvmissiletime);
		btnMissileTime = (Button) findViewById(R.id.btnmissiletime);
		btnMissileTime.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				ArrayAdapter<String> nameAdapter = new ArrayAdapter<String>(WorkAddActivity.this, android.R.layout.simple_list_item_single_choice);
				final int[] times;
				if (mFirearmType == FirearmType.MISSILE_83) {
					times = new int[] { 8, 10, 12, 14, 16, 18, 20 };
				} else {
					times = new int[] { 8, 10, 12, 14, 16, 18 };
				}
				for (int time : times) {
					nameAdapter.add(time + " 秒");
				}
				ListView listview = new ListView(WorkAddActivity.this);
				listview.setAdapter(nameAdapter);
				listview.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
						if (dialog != null) {
							dialog.dismiss();
						}
						tvMissileTime.setText(String.valueOf(times[arg2]));
						tvMissileAngle.setText("");
						tvMissileHeight.setText("");
						tvMissileLength.setText("");
					}
				});
				dialog = new AlertDialog.Builder(WorkAddActivity.this).setTitle("选择引信爆炸时间").setView(listview).show();
			}
		});
		tvMissileHeight = (TextView) findViewById(R.id.tvmissileheight);
		tvMissileLength = (TextView) findViewById(R.id.tvmissilelength);
		btnMissileQuery = (Button) findViewById(R.id.btnmissilequery);
		btnMissileQuery.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (etHaiba.getText().toString().trim().equals("")) {
					showToast("请输入作业站点海拔高度");
					etHaiba.requestFocus();
					return;
				}
				if (etCenterHeight.getText().toString().trim().equals("")) {
					showToast("请输入作业云系强度中心高度");
					etCenterHeight.requestFocus();
					return;
				}
				if (tvMissileTime.getText().toString().trim().equals("")) {
					showToast("请输入引信自炸时间");
					tvMissileTime.requestFocus();
					return;
				}

				int centerHeight = Integer.parseInt(etCenterHeight.getText().toString().trim());
				int haiba = Integer.parseInt(etHaiba.getText().toString().trim());
				int time = Integer.parseInt(tvMissileTime.getText().toString().trim());

				int height = centerHeight + haiba;

				switch (mFirearmType) {
				case FirearmType.MISSILE_83: {
					ArrayList<Missile83> missiles = Missile83Sql.getInstance().query(time);
					int i = 0;
					for (i = 0; i < missiles.size(); i++) {
						if (missiles.get(i).height >= height) {
							break;
						}
					}
					if (i == missiles.size()) {
						i--;
					}
					Missile83 m = missiles.get(i);
					tvMissileAngle.setText(String.valueOf(m.angel));
					//						tvMissileTime.setText(String.valueOf(m.time));
					tvMissileHeight.setText(String.valueOf(m.height));
					tvMissileLength.setText(String.valueOf(m.length));
					break;
				}
				case FirearmType.MISSILE_JD89: {
					ArrayList<MissileJD89> missiles = MissileJD89Sql.getInstance().query(time);
					int i = 0;
					for (i = 0; i < missiles.size(); i++) {
						if (missiles.get(i).height >= height) {
							break;
						}
					}
					if (i == missiles.size()) {
						i--;
					}
					MissileJD89 m = missiles.get(i);
					tvMissileAngle.setText(String.valueOf(m.angel));
					//						tvMissileTime.setText(String.valueOf(m.time));
					tvMissileHeight.setText(String.valueOf(m.height));
					tvMissileLength.setText(String.valueOf(m.length));
					break;
				}
				default:
					break;
				}
			}
		});

		btnFixedOrMove = (Button) findViewById(R.id.buttonfixedormove);
		btnFixedOrMove.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				ArrayAdapter<String> typeAdapter = new ArrayAdapter<String>(WorkAddActivity.this, android.R.layout.simple_list_item_single_choice);
				typeAdapter.add("固定作业点");
				typeAdapter.add("流动作业点");
				ListView listview = new ListView(WorkAddActivity.this);
				listview.setAdapter(typeAdapter);
				listview.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
						if (dialog != null) {
							dialog.dismiss();
						}
						if (arg2 == 0) {
							btnFixedOrMove.setText("固定作业点");
							isFixed = true;
							btnFixedPosition.setVisibility(View.VISIBLE);
						} else {
							btnFixedOrMove.setText("流动作业点");
							isFixed = false;
							btnFixedPosition.setVisibility(View.GONE);
						}
					}
				});
				dialog = new AlertDialog.Builder(WorkAddActivity.this).setTitle("选择作业点坐标类型").setView(listview).show();

			}
		});

		switch (mFirearmType) {
		case FirearmType.ROCKET_BL1:
			tvFirearmType.setText("BL-1型火箭弹");
			layoutMissile.setVisibility(View.GONE);
			break;
		case FirearmType.ROCKET_HJD82:
			tvFirearmType.setText("HJD-82型火箭弹");
			layoutMissile.setVisibility(View.GONE);
			break;
		case FirearmType.ROCKET_RY6300:
			tvFirearmType.setText("RYI-6300型火箭弹");
			layoutMissile.setVisibility(View.GONE);
			break;
		case FirearmType.ROCKET_WR98:
			tvFirearmType.setText("WR-98型火箭弹");
			layoutMissile.setVisibility(View.GONE);
			break;
		case FirearmType.MISSILE_83:
			tvFirearmType.setText("83型炮弹");
			layoutRocket.setVisibility(View.GONE);
			break;
		case FirearmType.MISSILE_JD89:
			tvFirearmType.setText("JD-89型炮弹");
			layoutRocket.setVisibility(View.GONE);
			break;
		default:
			layoutMissile.setVisibility(View.GONE);
			layoutRocket.setVisibility(View.GONE);
			break;
		}

	}

	@Override
	protected void openMenu() {
		String[] texts = new String[] { "火器选择", "添加站点", "历史查询", "退出程序" };
		Integer[] images = new Integer[] { R.drawable.menu_logout, R.drawable.menu_sys_add_buddy, R.drawable.menu_sys_search_buddy, R.drawable.menu_icon };
		mMenu = new MenuUtil(WorkAddActivity.this, getLayoutInflater().inflate(R.layout.workadd, null), texts, images);
		mMenu.setMenuItemSelectedLinstener(new OnClickListener() {

			public void onClick(View v) {
				int tag = (Integer) v.getTag();
				switch (tag) {
				case 0:
					mMenu.dismiss();
					Intent intent1 = new Intent(WorkAddActivity.this, ChoseFirearmActivity.class);
					intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent1);
					break;
				case 1:
					mMenu.dismiss();
					Intent intent2 = new Intent(WorkAddActivity.this, WorkStationAddActivity.class);
					intent2.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent2);
					break;
				case 2:
					mMenu.dismiss();
					Intent intent3 = new Intent(WorkAddActivity.this, HistoryQueryActivity.class);
					intent3.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent3);
					break;
				case 3:
					mMenu.dismiss();
					mDialog = new DialogUtil(WorkAddActivity.this);
					mDialog.setTitle("退出确认");
					mDialog.setMessage("确定退出吗？");
					mDialog.setPositiveButton("确定", new OnClickListener() {

						public void onClick(View v) {
							mDialog.dismiss();
							Intent intent = new Intent(WorkAddActivity.this, MainActivity.class);
							intent.putExtra("Flag", 1);
							intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
							startActivity(intent);
						}
					});
					mDialog.setNegativeButton("取消", null);
					mDialog.show();
					break;
				default:
					break;
				}
			}
		});
		mMenu.show();
	}

}
